package com.xrit.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.xrit.constant.MessageConstant;
import com.xrit.constant.RedisMessageConstant;
import com.xrit.pojo.Member;
import com.xrit.result.Result;
import com.xrit.service.MemberService;
import com.xrit.service.OrderService;
import com.xrit.utils.ValideCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 提交预约信息
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;

    @Reference
    private MemberService memberService;

    /**
     * 登录
     */
    @RequestMapping("/login")
    public Result login(@RequestBody  Map<String,String> paraMap, HttpServletResponse response){
        try{
            //1、校验用户输入的短信验证码是否正确，如果验证码错误则登录失败
            Result valid = ValideCodeUtils.isValid(jedisPool, paraMap, RedisMessageConstant.SENDTYPE_LOGIN);
            if (!valid.isFlag()){
                return valid;
            }
            //2、登录验证
            String telephone = paraMap.get("telephone");
            Member member = memberService.login(telephone);
            if (member!=null){
                //3、向客户端写入Cookie，内容为用户手机号
                //是会员：跟踪记录的手机号码，代表着会员
                Cookie cookie=new Cookie("login_member_telephone",telephone);
                cookie.setMaxAge(60*60*24*30);//保存30天
                cookie.setPath("/");//访问的路径：根路径下时,网站的所有路径,都会发送这个cookie
                response.addCookie(cookie);
                //4、将会员信息保存到redis，使用手机号作为key，保存时长为30分钟,实现数据共享
                String s = JSON.toJSON(member).toString();
                jedisPool.getResource().setex(telephone,30*60,s);
                return new Result(true,MessageConstant.LOGIN_SUCCESS);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return new Result(false,MessageConstant.LOGIN_FAIL);
    }
}
